// chrome.action.disable();// 删除现有规则，只应用我们的规则
// 点击跳转扩展页
// chrome.action.onClicked.addListener((tab) => {chrome.runtime.openOptionsPage();
// });

function contextMenus() {
  // chrome.contextMenus.create({
  //   id: "collectImageToSxj",
  //   title: "收藏此图片",
  //   contexts: ["image"],
  // });

  // chrome.contextMenus.create({
  //   parentId: "collectImageToSxj",
  //   id: "goToBaidu",
  //   title: "去百度",
  //   contexts: ["image"],
  // });
  // chrome.contextMenus.create({
  //   parentId: "collectImageToSxj",
  //   id: "search",
  //   title: "搜索",
  //   contexts: ["image"],
  // });

  chrome.contextMenus.create({
    id: "copyImageAddress",
    title: "复制图片地址",
    contexts: ["image"],
  });
  chrome.contextMenus.create({
    id: "downloadImg",
    title: "下载图片",
    contexts: ["image"],
  });

  // 实现谷歌翻译
  var menuItem = {
    id: "translate",
    title: "使用谷歌翻译",
    contexts: ["selection"],
  };
  chrome.contextMenus.create(menuItem);
}

// 接受内容页或者popup页发送的消息
chrome.runtime.onMessage.addListener(function (info, sender, sendResponse) {
  if (info.menuItemId == "urlDow") {
  }
});
contextMenus();

chrome.contextMenus.onClicked.addListener(async function (info, tab) {
  //收藏菜单

  if (info.menuItemId == "goToBaidu") {
    chrome.tabs.create({
      url:
        "https://www.baidu.com/s?ie=utf-8&wd=" + encodeURI(info.selectionText),
    });
  } else if (info.menuItemId == "search") {
    chrome.tabs.create({ url: "https://www.csdn.net" });
  } else if (info.menuItemId == "translate" && info.selectionText) {
    console.log(info.selectionText);
  } else if (info.menuItemId == "copyImageAddress") {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      // 查询当前活动窗口中的活动标签页
      chrome.tabs.sendMessage(tabs[0].id, { copy: "copy", text: info.srcUrl });
    });
  } else if (info.menuItemId == "downloadImg") {
    fetch(info.srcUrl)
      .then((response) => response.blob())
      .then((blob) => {
        // 现在你有了图像的 Blob  在转为base64 因为blob传不过去
        var reader = new FileReader();
        reader.onload = function () {
          var base64Data = reader.result;
          chrome.tabs.query(
            { active: true, currentWindow: true },
            function (tabs) {
              // 查询当前活动窗口中的活动标签页
              chrome.tabs.sendMessage(tabs[0].id, {
                copy: "download",
                blob: base64Data,
              });
            }
          );
        };
        reader.readAsDataURL(blob);
      })
      .catch((error) => console.error("Error fetching image:", error));
  }
});

/**
 * 短期链接
 */
//  给内容页发送消息
function sendMessageContent(message, callback) {
  chrome.tabs.query(
    { active: true, currentWindow: true },
    async function (tabs) {
      // 查询当前活动窗口中的活动标签页
      const response = await chrome.tabs.sendMessage(tabs[0].id, {
        greeting: "hello",
      });
    }
  );
}

//   页面的js文件发送来的通信
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  // 处理来自content script的消息
  if (request.msg === "Hello") {
    // 执行相应的操作
    sendResponse("Hello from content script!");
  } else if (request.msg === "contextMenus") {
    sendResponse({ farewell: "菜单创建成功 !!!" });
  }
});

/**
 * 长期链接
 */
chrome.runtime.onConnect.addListener(function (port) {
  port.onMessage.addListener(function (msg) {
    if (msg.menuItemId == "urlDow") {
      fetch(msg.url)
        .then((response) => response.blob())
        .then((blob) => {
          // 现在你有了图像的 Blob 对象，可以进行处理
          var reader = new FileReader();
          reader.onload = function () {
            var base64Data = reader.result;
            port.postMessage({ iurs: "12", blob: base64Data });
          };
          reader.readAsDataURL(blob);
        })
        .catch((error) => console.error("Error fetching image:", error));
    }
  });
  // port.onMessage.addListener(function (msg) {
  //   fetch(
  //     `http://photo-cd-dev.shixianjia.com/api/app/image-favorites/save-image-favorites`,
  //     {
  //       method: "POST",
  //       headers: {
  //         "Content-Type": "application/json",
  //         Authorization:
  //           "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9naXZlbm5hbWUiOiJhZG1pbiIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiJhZG1pbiIsImp0aSI6IjEyIiwiYWJwVXNlcklkIjoiMzJhMDEwNmItMDQxNi0xMWVlLWJhYjktMDI0MmFjMTIwMDA0Iiwic2hvcGlkIjoiMTIiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL2V4cGlyYXRpb24iOiIwMS8zMC8yMDI0IDEwOjE4OjIwIiwidGVuYW50SWQiOiI0NDZhNTIxMS0zZDcyLTQzMzktOWFkYy04NDUxNTFmOGFkYTAiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJTdXBlckFkbWluIiwibmJmIjoxNzA2NDk0NzAwLCJleHAiOjE3MDY1ODExMDAsImlzcyI6InBob3RvYWRtaW4iLCJhdWQiOiJQaG90b0FkbWluIn0.Eq4e_kSNnY4Clq_08Bf_eF1wROwDhJHtfy9qgMH2SCE",
  //       },
  //       body: JSON.stringify([
  //         {
  //           url: "https://sxj-course.oss-cn-shenzhen.aliyuncs.com/2023-12-08/487941b2ed2f41ba94c110358d423729.jpg",
  //         },
  //       ]),
  //     }
  //   )
  //     .then()
  //     .then((data) => {
  //       port.postMessage({ question: "收藏成功" });
  //     })
  //     .catch((error) => {
  //       port.postMessage({ question: "收藏失败" });
  //     });

  // if (msg.joke === "Knock knock"){

  // }else if (msg.answer === "Madame"){
  //   port.postMessage({question: "Madame who?"});
  // } else if (msg.answer === "Madame... Bovary"){
  //   port.postMessage({question: "I don't get it."});
  // }
  // });
});

/**
 * 关闭指定的长期的链接
 */

//  chrome.runtime.disconnect({name: "connectionName"});

/**
 * 动态注入脚本 注入式manifest.json就不能引入了 要不然不起作用
 */

//   chrome.scripting
// .registerContentScripts([{
//   id: "session-scr1ipt",
//   js: ["dynamicState.js"],
//   persistAcrossSessions: true,
//   matches: ["https://www.baidu.com/*"],
//   runAt: "document_end",
// }])
// .then((res) => console.log("registration complete",res))
// .catch((err) => console.log("322 error", err))

// 实现跨域

// chrome.webRequest.onBeforeSendHeaders.addListener(
//   function(details) {
//   console.log("发起请求：" + details.id);
//   // return {cancel: true}; // 取消请求
//   },
//   {urls: ["<all_urls>"]},
//   ["blocking"]
// );

// chrome.webRequest.handlerBehaviorChanged();
// .addListener(
//   function(details) {
//     // 在请求发起前进行处理
//     console.log("发起请求：" + details.url);
//   },
//   {urls: ["<all_urls>"]}, // 匹配所有 URL
//   ["blocking"] // 选项，表示是否阻止请求
// );
